#include "StdAfx.h"

#include <time.h>
#include <iostream>
#include <fstream>

#include "Recorder.h"
#include "WaveSample.h"
#include "WavFile.h"
#include "WaveletPitchProcessor.h"

Recorder::Recorder(void)
{
}

Recorder::~Recorder(void)
{
}

void Recorder::AddModulatorSample(Sample* s)
{
	modulatorSamples.push_back(s->Copy(1.0, 0));	
}

void Recorder::AddCarrierSample(Sample* s)
{
	carrierSamples.push_back(s->Copy(1.0, 0));
}

void Recorder::AddVocoderSample(Sample* s)
{
	vocoderSamples.push_back(s->Copy(1.0, 0));
}

void Recorder::AddPitchTrackerSample(PitchOut* p)
{
	pitchSamples.push_back(p);
}

void SaveSamplesToFile(SampleVector& samples, const char* filename)
{
	int size = samples.size();
	int sampleSize = 0;
	for(int i=0; i<size; i++)
	{
		Sample* sample = samples[i];
		sampleSize += sample->length;
	}
	Sample* allSamples = new Sample(sampleSize);
	register int idx=0;
	for(int i=0; i<size; i++)
	{
		Sample* sample = samples[i];
		for(int j=0; j<sample->length; j++, idx++)
		{
			allSamples->data[idx] = sample->data[j];
		}
	}
	WavFile::SaveToFile(filename, 1, 48000, allSamples);
	delete allSamples;
}

void ClearSamples(SampleVector& samples)
{
	for(int i=0; i<samples.size(); i++)
	{
		Sample* sample = samples[i];
		delete sample;
	}
	samples.clear();
}

void Recorder::SaveSamplesToFiles()
{
	//create a new folder with current time as its name	  
	time_t rawtime;
	time (&rawtime);  
	struct tm * timeinfo = localtime (&rawtime);
	TCHAR wdirname[17];
	wsprintf(wdirname, _T("%d-%d-%d-%d-%d\0"), timeinfo->tm_year+1900, timeinfo->tm_mon+1,
		timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min);
	CreateDirectory(wdirname, NULL);

	char dirname[18];
	sprintf(dirname, "%d-%d-%d-%d-%d\\\0", timeinfo->tm_year+1900, timeinfo->tm_mon+1,
		timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min);
	char modFile[32];
	char carrierFile[30];
	char vocoderFile[30];
	char pitchFile[27];
	sprintf(modFile, "%smodulator.wav\0", dirname);
	sprintf(carrierFile, "%scarrier.wav\0", dirname);
	sprintf(vocoderFile, "%svocoder.wav\0", dirname);
	sprintf(pitchFile, "%spitch.txt\0", dirname);

	//save each sample vector to a wav file
	SaveSamplesToFile(modulatorSamples, modFile);
	SaveSamplesToFile(carrierSamples, carrierFile);
	SaveSamplesToFile(vocoderSamples, vocoderFile);

	ClearSamples(modulatorSamples);
	ClearSamples(carrierSamples);
	ClearSamples(vocoderSamples);

	std::fstream ofile;
	ofile.open(pitchFile, std::ios::out);
	for(int i=0; i<pitchSamples.size(); i++)
	{
		PitchOut* pitch = pitchSamples[i];

		//write pitch line
		ofile << pitch->pitch << " " << pitch->level << " "
			<< pitch->signal_energy << " " << pitch->signal_high << " "
			<< pitch->signal_low << " " << pitch->voiced << std::endl;

		delete pitch;
	}
	pitchSamples.clear();
	ofile.close();

}
